package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.function.Consumer;


/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-06
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //校验老人是否已入住
        LambdaQueryWrapper<Elder> elderQuery = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQuery);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }
        //更新床位状态
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        //新增或更新老人信息
        elder = insertOrUpdate(bed, dto.getCheckInElderDto());
        //新增签约办理
        insertContract(dto, elder);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(dto, elder);
        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);

    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //查询老人信息
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, checkIn.getElderId()));
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId()));
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        //封装checkInElderVo
        CheckInElderVo checkInElderVo = getCheckInElderVo(checkIn, elder);
        //封装elderFamilyVoList
        List<ElderFamilyVo> elderFamilyVoList = getElderFamilyVoList(checkIn.getRemark());
        //封装checkInConfigVo
        CheckInConfigVo checkInConfigVo = getCheckInConfigVo(checkIn, checkInConfig);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    private CheckInConfigVo getCheckInConfigVo(CheckIn checkIn, CheckInConfig checkInConfig) {
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setDeposit(checkInConfig.getDeposit());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVo.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVo.setNursingFee(checkInConfig.getNursingFee());
        checkInConfigVo.setOtherFees(checkInConfig.getOtherFees());
        checkInConfigVo.setBedFee(checkInConfig.getBedFee());
        checkInConfigVo.setSortOrder(checkInConfig.getSortOrder());
        checkInConfigVo.setNursingLevelName(checkInConfig.getNursingLevelName());
        checkInConfigVo.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setCheckInId(checkIn.getId());
        checkInConfigVo.setId(checkInConfig.getId());
        checkInConfigVo.setCreateBy(checkInConfig.getCreateBy());
        checkInConfigVo.setCreateTime(checkInConfig.getCreateTime());
        checkInConfigVo.setUpdateTime(checkInConfig.getUpdateTime());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        return checkInConfigVo;
    }

    private List<ElderFamilyVo> getElderFamilyVoList(String remark) {
//        JSONArray objects = JSON.parseArray(remark);
//        List<ElderFamilyVo> elderFamilyVos = new ArrayList<>();
//        objects.forEach(new Consumer<Object>() {
//            @Override
//            public void accept(Object object) {
//                elderFamilyVos.add(JSON.parseObject(object.toString(), ElderFamilyVo.class));
//            }
//        });
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseObject(remark, new TypeReference<List<ElderFamilyVo>>() {});

        return elderFamilyVoList;
    }

    private CheckInElderVo getCheckInElderVo(CheckIn checkIn, Elder elder) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串解析为 LocalDate
        LocalDate birthDate = LocalDate.parse(elder.getBirthday(), formatter);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算年龄
        Period period = Period.between(birthDate, currentDate);
        int age = period.getYears();
        CheckInElderVo checkInElderVo = CheckInElderVo.builder()
                .id(checkIn.getElderId())
                .name(checkIn.getElderName())
                .idCardNo(checkIn.getIdCardNo())
                .birthday(elder.getBirthday())
                .sex(elder.getSex())
                .phone(elder.getPhone())
                .address(elder.getAddress())
                .image(elder.getImage())
                .idCardNationalEmblemImg(elder.getIdCardNationalEmblemImg())
                .idCardPortraitImg(elder.getIdCardPortraitImg())
                .age(age)
                .build();
        return checkInElderVo;
    }

    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(CheckInApplyDto dto, Elder elder) {
        //创建入住信息载体
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        //将家人信息转为json
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        //默认已入住
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(CheckInApplyDto dto, Elder elder) {
        //新增签约办理载体
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //生成合同编号
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        //获取签约，解约时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        //对比签约时间与当前时间，判断是已生效还是未生效
        int status = startDate.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(status);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //创建老人信息载体
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        //再次查询老人信息是否已存在，决定是新增or更新老人信息
        LambdaQueryWrapper<Elder> elderQuery = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elder.getIdCardNo())
                .ne(Elder::getStatus, 1);
        Elder elderDto = elderMapper.selectOne(elderQuery);
        if (ObjectUtils.isEmpty(elderDto)) {
            //新增
            elderMapper.insert(elder);
        } else {
            //更新
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
